package com.yc.pos;



import java.io.ByteArrayOutputStream;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Administrator on 2015-11-20.
 */
public class Record {
    public String id;
    public String recordNo;    //记录流水号 hex
    public int userNo;      //用户流水号
    public int balance;     //用户卡余额
    public int expenditure; //用户消费额
    public String time;       //消费时间 hex
    public short count;     //用户使用次数
    public String address;   //设备地址 10进制字符串

    public byte[] encode() {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(DigitalUtil.HexString2Bytes(recordNo, 4),0,4);   //4个字节
        outputStream.write(DigitalUtil.int2bytesBy32(userNo), 1, 3);  //3个字节
        outputStream.write(DigitalUtil.int2bytesBy32(balance), 1, 3);  //3个字节
        outputStream.write(DigitalUtil.int2bytesBy32(expenditure), 1, 3);  //3个字节
        byte[] oTime = DigitalUtil.HexString2Bytes(time);
        outputStream.write(oTime, 0, oTime.length);   //6个字节
        outputStream.write(DigitalUtil.shortToByteArray(count), 0, 2);    //2个字节
        byte[] key = new byte[2];
        key[1] = 0x34;
        outputStream.write(key, 0, 2); //2个字节
        outputStream.write(new byte[5], 0, 5); //5个字节
        String hexAddress = DigitalUtil.decInt2HexString(Integer.valueOf(address));
        String  tempHex = DigitalUtil.StrReverseByte(hexAddress);
        byte[] oAddress = DigitalUtil.HexString2Bytes(tempHex);
        if(oAddress.length<2) {
            byte[] ad = new byte[2];
            if(oAddress.length>0){
                ad[0] = oAddress[0];
            }
            outputStream.write(ad, 0, 2);
        } else {
            outputStream.write(oAddress, 0, oAddress.length);
        }
        outputStream.write(new byte[2],0,2); //2个字节
        byte[] b =  outputStream.toByteArray();
        return outputStream.toByteArray();

    }

    /**
     * 将时间转换为16进制字节数组
     *
     * @param date
     * @return
     */
    private byte[] getHexTimeString(Date date) {
        byte[] ret = new byte[6];
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR) - 2000;
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        ret[0] = Byte.parseByte(String.valueOf(year), 10);
        ret[1] = Byte.parseByte(String.valueOf(month), 10);
        ret[2] = Byte.parseByte(String.valueOf(day), 10);
        ret[3] = Byte.parseByte(String.valueOf(hour), 10);
        ret[4] = Byte.parseByte(String.valueOf(minute), 10);
        ret[5] = Byte.parseByte(String.valueOf(second), 10);
        return ret;
    }

}
